package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import com.sun.xml.internal.ws.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by IntelliJ IDEA.
 * Description:
 * User: 35391
 * Package: com.sky.service.impl
 * Date: 2025/7/18
 * Time: 下午3:21
 * Version: 1.0
 */
@Service
@Slf4j
public class ReportServiceImpl implements ReportService{
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService  workSpaceService;
    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //该集合用于存放从begin到end的每一天
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            //日期计算，begin加1天
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //获取日期对应的营业额数据,只统计状态为"已完成"的订单
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            if(turnover == null){
                turnover = 0.0;
            }
            log.info("日期 {} 的营业额为：{}", date, turnover);
            turnoverList.add(turnover);
        }

        // 将 LocalDate 列表转换为 String 列表
        List<String> dateStringList = dateList.stream()
                .map(date -> date.format(DateTimeFormatter.ISO_LOCAL_DATE))
                .collect(Collectors.toList());

        // 将 Double 列表转换为 String 列表
        List<String> turnoverStringList = turnoverList.stream()
                .map(amount -> String.format("%.2f", amount))
                .collect(Collectors.toList());

        return TurnoverReportVO.builder()
                .dateList(String.join(",", dateStringList))
                .turnoverList(String.join(",", turnoverStringList)) // 使用 java.util.String 的 join 方法
                .build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();

        for(LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("endTime", endTime);

            //总用户数
            totalUserList.add(userMapper.countByMap(map));
            //新增用户数
            map.put("beginTime", beginTime);
            newUserList.add(userMapper.countByMap(map));
        }

        // 将 LocalDate 列表转换为 String 列表
        List<String> dateStringList = dateList.stream()
                .map(date -> date.format(DateTimeFormatter.ISO_LOCAL_DATE))
                .collect(Collectors.toList());
        // 将 Integer 列表转换为 String 列表
        List<String> totalUserStringList = totalUserList.stream()
                .map(amount -> String.format("%d", amount))
                .collect(Collectors.toList());
        // 将 Integer 列表转换为 String 列表
        List<String> newUserStringList = newUserList.stream()
                .map(amount -> String.format("%d", amount))
                .collect(Collectors.toList());
        return UserReportVO.builder()
                .dateList(String.join(",", dateStringList))
                .totalUserList(String.join(",", totalUserStringList))
                .newUserList(String.join(",", newUserStringList))
                .build();
    }

    /**
     * 订单
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            orderCountList.add(orderMapper.countByMap(map));
            map.put("status", Orders.COMPLETED);
            validOrderCountList.add(orderMapper.countByMap(map));
        }
        //计算时间区间内的订单总数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //计算时间区间内的有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //计算订单完成率
        Double orderCompletionRate = totalOrderCount == 0 ? 0.00 : validOrderCount.doubleValue() / totalOrderCount;

        // 将 LocalDate 列表转换为 String 列表
        List<String> dateStringList = dateList.stream()
                .map(date -> date.format(DateTimeFormatter.ISO_LOCAL_DATE))
                .collect(Collectors.toList());
        // 将 Integer 列表转换为 String 列表
        List<String> orderCountStringList = orderCountList.stream()
                .map(amount -> String.format("%d", amount))
                .collect(Collectors.toList());
        // 将 Integer 列表转换为 String 列表
        List<String> validOrderCountStringList = validOrderCountList.stream()
                .map(amount -> String.format("%d", amount))
                .collect(Collectors.toList());

        return OrderReportVO.builder()
                .dateList(String.join(",", dateStringList ))
                .orderCountList(String.join(",", orderCountStringList))
                .validOrderCountList(String.join(",", validOrderCountStringList))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销量排名top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        // 将商品名称列表转换为逗号分隔的字符串
        String nameList= salesTop10.stream()
                .map(GoodsSalesDTO::getName)
                .collect(Collectors.joining(","));
        // 将销量列表转换为逗号分隔的字符串
        String numberList = salesTop10.stream()
                .map(GoodsSalesDTO::getNumber)
                .map(String::valueOf) // 将 Integer 转换为 String
                .collect(Collectors.joining(","));
        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //查询数据库，获取营业数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        LocalDateTime begin = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(dateEnd, LocalTime.MAX);
        BusinessDataVO businessDataVO = workSpaceService.getBusinessData(begin, end);
        //通过POI将数据写入excel
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于模板文件创建一个新的excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //获取表格文件的sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);
            //填充数据--营业额(第四行)
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            //填充数据--订单完成率(第四行)
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            //填充数据--新用户数(第四行)
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            //填充数据--有效订单数(第五行)
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            //填充数据--平均客单价(第五行)
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充数据--明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的数据
                BusinessDataVO businessData = workSpaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                //获得某一行
                row = sheet.getRow(7 + i);
                //填充日期
                row.getCell(1).setCellValue(date.toString());
                //填充营业额
                row.getCell(2).setCellValue(businessData.getTurnover());
                //填充有效订单数
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                //填充订单完成率
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                //填充平均客单价
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                //填充新用户数
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //通过输出流将excel文件下载到客户端
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
